package org.linlinjava.litemall.wx.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallChatSession;
import org.linlinjava.litemall.db.domain.LitemallMessage;
import org.linlinjava.litemall.db.domain.LitemallGoods;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.linlinjava.litemall.wx.service.WxMessageService;
import org.linlinjava.litemall.db.service.LitemallGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/wx/message")
@Validated
public class WxMessageController {
    private final Log logger = LogFactory.getLog(WxMessageController.class);

    @Autowired
    private WxMessageService messageService;

    @Autowired
    private LitemallGoodsService goodsService;

    /**
     * 发送消息
     */
    @PostMapping("/send")
    public Object send(@RequestBody LitemallMessage message) {
        if (message.getSenderId() == null) {
            return ResponseUtil.unlogin();
        }

        // 参数验证
        if (message.getReceiverId() == null || message.getContent() == null) {
            return ResponseUtil.badArgument();
        }

        try {
            logger.info("发送消息: " + message.toString());
            int result = messageService.sendMessage(message);
            if (result > 0) {
                logger.info("消息发送成功，ID: " + message.getId());
                Map<String, Object> data = new HashMap<>();
                data.put("messageId", message.getId());
                data.put("createTime", message.getCreateTime());
                return ResponseUtil.ok(data);
            } else {
                logger.error("消息发送失败");
                return ResponseUtil.fail(-1, "发送失败");
            }
        } catch (Exception e) {
            logger.error("发送消息失败", e);
            return ResponseUtil.fail(-1, "发送失败：" + e.getMessage());
        }
    }

    /**
     * 获取消息列表
     */
    @GetMapping("/list")
    public Object list(@LoginUser Integer loginUserId,
                       @RequestParam(required = false) String userId,
                       @RequestParam String partnerId,
                       @RequestParam(required = false,name = "productId") Integer productId,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "20") Integer size) {

        // 优先使用登录用户ID，如果没有则使用请求参数中的userId（用于测试）
        String actualUserId = loginUserId != null ? loginUserId.toString() : userId;
        
        if (actualUserId == null) {
            return ResponseUtil.unlogin();
        }
        if (partnerId == null) {
            return ResponseUtil.badArgument();
        }
        
        try {
            List<LitemallMessage> messages = messageService.getMessageList(
                actualUserId, 
                partnerId, 
                (page-1)*size, 
                size,productId
            );
            return ResponseUtil.ok(messages);
        } catch (Exception e) {
            return ResponseUtil.fail(-1, "获取消息失败");
        }
    }

    /**
     * 获取聊天会话列表
     */
    @GetMapping("/chatList")
    public Object getChatList(@LoginUser Integer loginUserId,
                              @RequestParam(required = false) String userId) {
        // 优先使用登录用户ID，如果没有则使用请求参数中的userId（用于测试）
        String actualUserId = loginUserId != null ? loginUserId.toString() : userId;
        
        if (actualUserId == null) {
            return ResponseUtil.unlogin();
        }
        
        logger.info("获取用户 " + actualUserId + " 的聊天列表");
        List<LitemallChatSession> chatList = messageService.getChatList(actualUserId);
        logger.info("查询结果: " + chatList);
        return ResponseUtil.ok(chatList);
    }

    /**
     * 标记消息已读
     */
    @PostMapping("/read")
    public Object markRead(@LoginUser Integer loginUserId,
                          @RequestParam(required = false) String userId,
                          @RequestParam String partnerId) {
        // 优先使用登录用户ID，如果没有则使用请求参数中的userId（用于测试）
        String actualUserId = loginUserId != null ? loginUserId.toString() : userId;
        
        if (actualUserId == null) {
            return ResponseUtil.unlogin();
        }

        int result = messageService.markMessageRead(actualUserId, partnerId);

        return ResponseUtil.ok(result);
    }

    /**
     * 获取未读消息数
     */
    @GetMapping("/unread")
    public Object getUnreadCount(@LoginUser Integer loginUserId,
                                @RequestParam(required = false) String userId,
                                @RequestParam String partnerId) {
        // 优先使用登录用户ID，如果没有则使用请求参数中的userId（用于测试）
        String actualUserId = loginUserId != null ? loginUserId.toString() : userId;
        
        if (actualUserId == null) {
            return ResponseUtil.unlogin();
        }

        int count = messageService.getUnreadCount(actualUserId, partnerId);
        Map<String, Object> data = new HashMap<>();
        data.put("count", count);
        return ResponseUtil.ok(data);
    }

    /**
     * 获取所有未读消息数
     */
    @GetMapping("/unread/total")
    public Object getTotalUnreadCount(@LoginUser Integer loginUserId,
                                     @RequestParam(required = false) String userId) {
        // 优先使用登录用户ID，如果没有则使用请求参数中的userId（用于测试）
        String actualUserId = loginUserId != null ? loginUserId.toString() : userId;
        
        if (actualUserId == null) {
            return ResponseUtil.unlogin();
        }

        List<LitemallChatSession> chatList = messageService.getChatList(actualUserId);
        int totalCount = chatList.stream()
                .mapToInt(chat -> chat.getUnreadCount())
                .sum();

        Map<String, Object> data = new HashMap<>();
        data.put("count", totalCount);
        return ResponseUtil.ok(data);
    }

    /**
     * 获取聊天详情
     */
    @GetMapping("/chatDetail")
    public Object getChatDetail(@LoginUser Integer loginUserId,
                               @RequestParam(required = false) String userId,
                               @RequestParam String partnerId) {
        // 优先使用登录用户ID，如果没有则使用请求参数中的userId（用于测试）
        String actualUserId = loginUserId != null ? loginUserId.toString() : userId;
        
        if (actualUserId == null) {
            return ResponseUtil.unlogin();
        }
        if (partnerId == null) {
            return ResponseUtil.badArgument();
        }

        try {
            // 1. 获取会话信息
            LitemallChatSession chatSession = messageService.getChatList(actualUserId)
                .stream()
                .filter(session -> session.getPartnerId().equals(partnerId))
                .findFirst()
                .orElse(null);

            if (chatSession == null) {
                return ResponseUtil.fail(404, "会话不存在");
            }

            // 2. 构建返回数据
            Map<String, Object> data = new HashMap<>();
            
            // 3. 添加会话基本信息
            Map<String, Object> sessionInfo = new HashMap<>();
            sessionInfo.put("partnerId", chatSession.getPartnerId());
            sessionInfo.put("partnerName", chatSession.getPartnerName());
            sessionInfo.put("partnerAvatar", chatSession.getPartnerAvatar());
            sessionInfo.put("lastMessage", chatSession.getLastMessage());
            data.put("sessionInfo", sessionInfo);

            // 4. 如果存在商品ID，查询商品信息
            if (chatSession.getProductId() != null && chatSession.getProductId() > 0) {
                LitemallGoods goods = goodsService.findById(chatSession.getProductId());
                if (goods != null && goods.getIsOnSale() && !goods.getDeleted()) {
                    Map<String, Object> productInfo = new HashMap<>();
                    productInfo.put("id", goods.getId());
                    productInfo.put("name", goods.getName());
                    productInfo.put("img", goods.getPicUrl());
                    productInfo.put("price", goods.getCounterPrice());
                    productInfo.put("brief", goods.getBrief());
                    data.put("productInfo", productInfo);
                }
            }

            return ResponseUtil.ok(data);
        } catch (Exception e) {
            logger.error("获取聊天详情失败", e);
            return ResponseUtil.fail(-1, "获取聊天详情失败");
        }
    }

    @PostMapping("/create")
    public Object createChat(@LoginUser Integer loginUserId,
                            @RequestParam(required = false) String userId,
                            @RequestBody Map<String, Object> body) {
        // 优先使用登录用户ID，如果没有则使用请求参数中的userId（用于测试）
        Integer actualUserId = loginUserId != null ? loginUserId : (userId != null ? Integer.valueOf(userId) : null);
        
        if (actualUserId == null) {
            return ResponseUtil.unlogin();
        }

        Integer sellerId = (Integer) body.get("sellerId");
        Integer productId = (Integer) body.get("productId");
        
        if (sellerId == null || productId == null) {
            return ResponseUtil.badArgument();
        }

        try {
            // 创建或获取会话
            LitemallChatSession chatSession = new LitemallChatSession();
            chatSession.setUserId(actualUserId.toString());
            chatSession.setPartnerId(sellerId.toString());
            chatSession.setProductId(productId);
            chatSession.setCreateTime(LocalDateTime.now());
            chatSession.setUpdateTime(LocalDateTime.now());
            
            // 发送系统消息
            LitemallMessage message = new LitemallMessage();
            message.setSenderId(actualUserId.toString());
            message.setReceiverId(sellerId.toString());
            message.setType("system");
            message.setProductId(productId);
            message.setContent("对方对您的商品感兴趣");
            message.setCreateTime(new Date());
            
            // 保存会话和消息
            messageService.createChat(chatSession, message);

            Map<String, Object> data = new HashMap<>();
            data.put("chatId", chatSession.getId());
            return ResponseUtil.ok(data);
        } catch (Exception e) {
            logger.error("创建聊天失败", e);
            return ResponseUtil.fail(-1, "创建聊天失败");
        }
    }
}